<template>
  <div class="train-tickets-container">
    <div style="height: 5px;"></div>
    <!-- 显示火车票列表 -->
    <div v-if="parsedTickets && parsedTickets.length > 0">
        <div v-for="(ticket, index) in parsedTickets" :key="index" class="train-ticket-card" @click="toggleExpand(index)">
            <!-- 主要信息区域 -->
            <div class="ticket-main">
                <div class="time-info">
                    <div class="departure">
                        <div class="time">{{ ticket.start_time }}</div>
                        <div class="station">{{ ticket.from_station }}</div>
                    </div>
                    <div class="duration-info">
                        <div class="duration">{{ formatDuration(ticket.lishi) }}</div>
                        <div class="train-number">{{ ticket.start_train_code }}</div>
                        <div v-if="ticket.dw_flag && ticket.dw_flag.length > 0" class="train-tags">
                            <span v-for="flag in ticket.dw_flag" :key="flag" class="tag">{{ flag }}</span>
                        </div>
                    </div>
                    <div class="arrival-with-icon">
                        <div class="arrival">
                            <div class="time">{{ ticket.arrive_time }}</div>
                            <div class="station">{{ ticket.to_station }}</div>
                        </div>
                        <!-- 展开图标 -->
                        <div class="expand-icon" :class="{ 'expanded': expandedTickets.includes(index) }">
                            <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
                                <path d="M3 4.5L6 7.5L9 4.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                            </svg>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 展开的详细信息区域 -->
            <div v-if="expandedTickets.includes(index)" class="ticket-details">
                <div class="details-header">座位类型及余票</div>
                <div class="seat-details">
                    <div v-for="price in ticket.prices" :key="price.seat_name" class="seat-detail-item">
                        <span class="seat-type">{{ price.seat_name }}</span>
                        <div class="seat-info">
                            <div class="seat-availability" :class="getAvailabilityClass(price.num)">
                                {{ formatAvailability(price.num) }}
                            </div>
                            <span class="seat-price">¥{{ formatPrice(price.num, price.price) }}</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    

    <!-- 当没有数据时显示提示信息 -->
    <div v-if="props.tickets && (!parsedTickets || parsedTickets.length === 0)" class="no-tickets">
        <p>{{ parseErrorMessage || '暂无车次信息' }}</p>
    </div>
    
    <!-- 默认模板 -->
    <div v-if="!props.tickets" class="train-ticket-card">
        <div class="ticket-main">
            <div class="time-info">
                <div class="departure">
                    <div class="time">09:00</div>
                    <div class="station">吉安</div>
                </div>
                <div class="duration-info">
                    <div class="duration">4小时30分</div>
                    <div class="train-number">G1033</div>
                    <div class="train-tags">
                        <span class="tag">复兴号</span>
                    </div>
                </div>
                <div class="arrival-with-icon">
                    <div class="arrival">
                        <div class="time">13:30</div>
                        <div class="station">南昌</div>
                    </div>
                    <div class="expand-icon">
                        <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
                            <path d="M3 4.5L6 7.5L9 4.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                        </svg>
                    </div>
                </div>
            </div>
        </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineProps, computed, ref } from 'vue';

// 展开状态管理
const expandedTickets = ref<number[]>([]);

// 切换展开状态
const toggleExpand = (index: number) => {
  const expandIndex = expandedTickets.value.indexOf(index);
  if (expandIndex > -1) {
    expandedTickets.value.splice(expandIndex, 1);
  } else {
    expandedTickets.value.push(index);
  }
};

// 定义12306-mcp返回的火车票数据类型
interface Price {
  seat_name: string;
  short: string;
  seat_type_code: string;
  num: string;
  price: number;
  discount?: number | null;
}

interface TicketInfo {
  train_no: string;
  start_date: string;
  arrive_date: string;
  start_train_code: string;
  start_time: string;
  arrive_time: string;
  lishi: string;
  from_station: string;
  to_station: string;
  from_station_telecode: string;
  to_station_telecode: string;
  prices: Price[];
  dw_flag: string[];
}

// 接收props
const props = defineProps<{
  tickets?: string | TicketInfo[];
}>();

// 解析错误信息
const parseErrorMessage = computed(() => {
  if (typeof props.tickets === 'string') {
    if (props.tickets.includes('没有查询到相关车次信息')) {
      return '没有查询到相关车次信息，请尝试其他日期或路线';
    }
    if (props.tickets.includes('Error:')) {
      return '查询出现错误，请稍后重试';
    }
    return null;
  }
  return null;
});

// 解析火车票数据
const parsedTickets = computed(() => {
  if (!props.tickets) {
    return [];
  }
  
  console.log('原始票据数据:', props.tickets);
  console.log('数据类型:', typeof props.tickets);
  
  // 如果是字符串，尝试解析
  if (typeof props.tickets === 'string') {
    try {
      // 检查是否是错误信息
      if (props.tickets.includes('Error:') || props.tickets.includes('没有查询到')) {
        return [];
      }
      
      // 尝试解析12306-mcp返回的文本格式
      const result = parseTicketText(props.tickets);
      console.log('解析后的票据数据:', result);
      return result;
    } catch (error) {
      console.error('解析火车票数据失败:', error);
      return [];
    }
  }
  
  // 如果已经是数组格式，直接返回
  if (Array.isArray(props.tickets)) {
    console.log('数组格式的票据数据:', props.tickets);
    return props.tickets;
  }
  
  return [];
});



// 解析12306-mcp返回的文本格式火车票数据
const parseTicketText = (text: string): TicketInfo[] => {
  const tickets: TicketInfo[] = [];
  const lines = text.split('\n').filter(line => line.trim() && !line.includes('车次 |'));
  
  for (const line of lines) {
    if (line.trim() && !line.startsWith('-')) {
      try {
        // 解析每行的火车票信息
        // 格式: G1033(实际车次train_no: 240000G10336) 南昌西(telecode: NCG) -> 深圳北(telecode: SZQ) 09:00 -> 13:30 历时：4:30
        const mainMatch = line.match(/^([A-Z]\d+)\(实际车次train_no:\s*([^)]+)\)\s+([^(]+)\(telecode:\s*([^)]+)\)\s*->\s*([^(]+)\(telecode:\s*([^)]+)\)\s+(\d{2}:\d{2})\s*->\s*(\d{2}:\d{2})\s+历时：(\d+:\d+)/);
        
        if (mainMatch) {
          const [, trainCode, trainNo, fromStation, fromCode, toStation, toCode, startTime, arriveTime, duration] = mainMatch;
          
          const ticket: TicketInfo = {
            train_no: trainNo.trim(),
            start_date: new Date().toISOString().split('T')[0], // 默认今天
            arrive_date: new Date().toISOString().split('T')[0], // 默认今天
            start_train_code: trainCode.trim(),
            start_time: startTime.trim(),
            arrive_time: arriveTime.trim(),
            lishi: duration.trim(),
            from_station: fromStation.trim(),
            to_station: toStation.trim(),
            from_station_telecode: fromCode.trim(),
            to_station_telecode: toCode.trim(),
            prices: [],
            dw_flag: []
          };
          
          tickets.push(ticket);
        }
      } catch (error) {
        console.error('解析单行火车票数据失败:', error, line);
      }
    } else if (line.startsWith('-') && tickets.length > 0) {
      // 解析票价信息
      try {
        // 格式: - 二等座: 有票 235元
        const priceMatch = line.match(/-\s*([^:]+):\s*([^0-9]+)\s*(\d+)元/);
        if (priceMatch) {
          const [, seatName, availability, price] = priceMatch;
          const lastTicket = tickets[tickets.length - 1];
          lastTicket.prices.push({
            seat_name: seatName.trim(),
            short: getSeatShort(seatName.trim()),
            seat_type_code: '',
            num: availability.trim(),
            price: parseInt(price),
            discount: null
          });
        }
      } catch (error) {
        console.error('解析票价信息失败:', error, line);
      }
    }
  }
  
  return tickets;
};

// 获取座位类型简称
const getSeatShort = (seatName: string): string => {
  const seatMap: Record<string, string> = {
    '商务座': 'swz',
    '特等座': 'tz',
    '一等座': 'zy',
    '二等座': 'ze',
    '高级软卧': 'gr',
    '软卧': 'rw',
    '硬卧': 'yw',
    '软座': 'rz',
    '硬座': 'yz',
    '无座': 'wz'
  };
  return seatMap[seatName] || 'qt';
};

// 格式化时长
const formatDuration = (duration: string): string => {
  if (duration.includes('小时') && duration.includes('分')) {
    return duration;
  }
  
  // 处理 HH:MM 格式
  const parts = duration.split(':');
  if (parts.length === 2) {
    const hours = parseInt(parts[0]);
    const minutes = parseInt(parts[1]);
    
    if (hours > 0 && minutes > 0) {
      return `${hours}小时${minutes}分`;
    } else if (hours > 0) {
      return `${hours}小时`;
    } else if (minutes > 0) {
      return `${minutes}分`;
    }
  }
  
  return duration;
};

// 格式化票量信息
const formatAvailability = (num: string): string => {
  if (!num) return '无票';
  
  // 清理数据，移除多余的数字和符号
  let cleanNum = num.toString().trim();
  
  // 移除末尾的数字和点号（如 "无票 83." -> "无票"）
  cleanNum = cleanNum.replace(/\s+\d+\.?$/, '');
  
  // 检查是否为纯数字
  if (cleanNum.match(/^\d+$/)) {
    const count = parseInt(cleanNum);
    if (count === 0) {
      return '无票';
    } else if (count > 10) {
      return '充足';
    } else {
      return `${count}张`;
    }
  }
  
  // 处理特殊状态
  switch (cleanNum.trim()) {
    case '有':
    case '有票':
    case '充足':
      return '有票';
    case '无':
    case '无票':
    case '--':
    case '':
      return '无票';
    case '候补':
      return '候补';
    default:
      return cleanNum;
  }
};

// 格式化价格信息
const formatPrice = (num: string, price: number): string => {
  if (!num) return price.toString();
  
  // 从num中提取价格部分（如 "无票 83." -> "83."）
  const priceMatch = num.toString().match(/\s+(\d+\.?\d*)$/);
  if (priceMatch) {
    const numPrice = priceMatch[1];
    // 组合价格：83. + 5 = 83.5
    return `${numPrice}${price}`;
  }
  
  return price.toString();
};

// 获取票量状态的CSS类
const getAvailabilityClass = (num: string): string => {
  const availability = formatAvailability(num);
  if (availability === '无票' || availability === '候补') {
    return 'unavailable';
  } else if (availability === '有票' || availability === '充足' || availability.includes('张')) {
    return 'available';
  }
  return 'limited';
};
</script>

<style scoped lang="less"> 
.train-tickets-container {
    width: 100%;
    
    .train-ticket-card {
        width: 100%;
        background: #fff;
        border-radius: 12px;
        margin-bottom: 12px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
        border: 1px solid #f0f0f0;
        cursor: pointer;
        transition: all 0.3s ease;
        
        &:hover {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
            border-color: #e0e0e0;
        }
        
        .ticket-main {
            padding: 16px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            
            .time-info {
                display: flex;
                align-items: center;
                flex: 1;
                
                .departure {
                    text-align: center;
                    min-width: 80px;
                    
                    .time {
                        font-size: 20px;
                        font-weight: 600;
                        color: #333;
                        line-height: 1.2;
                    }
                    
                    .station {
                        font-size: 14px;
                        color: #666;
                        margin-top: 4px;
                    }
                }
                
                .arrival-with-icon {
                    display: flex;
                    align-items: center;
                    gap: 12px;
                    
                    .arrival {
                        text-align: center;
                        min-width: 80px;
                        
                        .time {
                            font-size: 20px;
                            font-weight: 600;
                            color: #333;
                            line-height: 1.2;
                        }
                        
                        .station {
                            font-size: 14px;
                            color: #666;
                            margin-top: 4px;
                        }
                    }
                }
                
                .duration-info {
                    flex: 1;
                    text-align: center;
                    margin: 0 20px;
                    
                    .duration {
                        font-size: 13px;
                        color: #999;
                        margin-bottom: 4px;
                    }
                    
                    .train-number {
                        font-size: 16px;
                        font-weight: 600;
                        color: #1890ff;
                        margin-bottom: 6px;
                    }
                    
                    .train-tags {
                        display: flex;
                        justify-content: center;
                        gap: 4px;
                        flex-wrap: wrap;
                        
                        .tag {
                            font-size: 10px;
                            padding: 2px 6px;
                            background: #f0f9ff;
                            color: #1890ff;
                            border-radius: 8px;
                            border: 1px solid #e6f7ff;
                        }
                    }
                }
            }
            
                .expand-icon {
                    color: #999;
                    transition: transform 0.3s ease;
                    cursor: pointer;
                    
                    &.expanded {
                        transform: rotate(180deg);
                    }
                }
        }
        
        .ticket-details {
            border-top: 1px solid #f0f0f0;
            padding: 16px;
            background: #fafafa;
            border-radius: 0 0 12px 12px;
            
            .details-header {
                font-size: 14px;
                font-weight: 500;
                color: #333;
                margin-bottom: 12px;
            }
            
            .seat-details {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
                gap: 12px;
                
                .seat-detail-item {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    padding: 8px 12px;
                    background: #fff;
                    border-radius: 8px;
                    border: 1px solid #f0f0f0;
                    
                    .seat-type {
                        font-size: 14px;
                        color: #333;
                        font-weight: 500;
                        flex: 0 0 auto;
                        min-width: 50px;
                    }
                    
                    .seat-info {
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                        flex: 1;
                        margin-left: 12px;
                        
                        .seat-availability {
                            font-size: 12px;
                            padding: 4px 8px;
                            border-radius: 6px;
                            font-weight: 500;
                            text-align: center;
                            flex: 1;
                            margin: 0 12px;
                            
                            &.available {
                                background: #f6ffed;
                                color: #52c41a;
                            }
                            
                            &.limited {
                                background: #fff7e6;
                                color: #fa8c16;
                            }
                            
                            &.unavailable {
                                background: #fff2f0;
                                color: #ff4d4f;
                            }
                        }
                        
                        .seat-price {
                            font-size: 16px;
                            font-weight: 600;
                            color: #1890ff;
                            text-align: right;
                            flex: 0 0 auto;
                            min-width: 60px;
                        }
                    }
                }
            }
        }
    }
    
    .no-tickets {
        text-align: center;
        padding: 40px 20px;
        color: #666;
        background-color: #f9f9f9;
        border-radius: 12px;
        
        p {
            margin: 0;
            font-size: 16px;
        }
    }
}

// 响应式设计
@media (max-width: 768px) {
    .train-tickets-container {
        .train-ticket-card {
            .ticket-main {
                flex-direction: column;
                gap: 16px;
                
                .time-info {
                    width: 100%;
                    
                    .duration-info {
                        margin: 0 16px;
                    }
                }
                
                .arrival-with-icon {
                    justify-content: center;
                    
                    .expand-icon {
                        margin-left: 8px;
                    }
                }
            }
            
            .ticket-details {
                .seat-details {
                    grid-template-columns: 1fr;
                }
            }
        }
    }
}
</style>